﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace DragonSolution.Web.Common.Common
{
    public class StringUtil
    {
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str">要截取的字符串</param>
        /// <param name="length">截取长度</param>
        /// <returns></returns>
        public static string CutString(string str, int length)
        {
            if (str.Length <= length)
            {
                return str;
            }
            else
            {
                return str.Substring(0, length) + "...";
            }
        }

        ///   <summary>
        ///   MD5加密
        ///   </summary>
        ///   <param   name="str">待加密字符串</param>
        ///   <returns>加密后的字符串</returns>
        public static string MD5Encrypt(string str)
        {
            MD5 md5 = MD5.Create();
            byte[] bytes = Encoding.ASCII.GetBytes(str);
            byte[] hashBytes = md5.ComputeHash(bytes);
            
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 输出时间,如“5分钟前”，“10小时前”
        /// </summary>
        /// <param name="time">时间对象</param>
        /// <returns></returns>
        public static string ShowTime(DateTime time)
        {
            string result = string.Empty;
            if (time > Convert.ToDateTime("1901-01-01"))
            {
                DateTime nowTime = DateTime.Now;//当前时间
                TimeSpan span = nowTime - time;
                if (span.TotalDays > 1)
                {
                    result = time.ToString("yyyy-MM-dd");
                }
                else
                {
                    if (span.TotalHours > 1)
                    {
                        result = (int)Math.Floor(span.TotalHours) + "小时前";
                    }
                    else
                    {
                        if (span.TotalMinutes > 1)
                        {
                            result = (int)Math.Floor(span.TotalMinutes) + "分钟前";
                        }
                        else
                        {
                            if (span.TotalSeconds >= 1)
                            {
                                result = (int)Math.Floor(span.TotalSeconds) + "秒钟前";
                            }
                            else
                            {
                                result = "1秒钟前";
                            }
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 删除文章中的图片
        /// </summary>
        /// <param name="htmlText">源文章</param>
        /// <returns></returns>
        public static void DelectHtmlImgList(string htmlText)
        {
            if (!string.IsNullOrEmpty(htmlText))
            {
                string[] urlList = GetHtmlImgUrlList(htmlText);
                if (urlList != null)
                {
                    foreach (var url in urlList)
                    {
                        FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("~") + url);
                        if (fi.Exists)
                            fi.Delete();
                    }
                }
            }
        }
        /// <summary>
        /// 得到文章中的图片路径集合
        /// </summary>
        /// <param name="htmlText">源文章</param>
        /// <returns></returns>
        public static string[] GetHtmlImgUrlList(string htmlText)
        {
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            if (!string.IsNullOrEmpty(htmlText))
            {
                // 搜索匹配的图片路径字符串 
                MatchCollection matches = regImg.Matches(htmlText);
                if (matches.Count > 0)
                {
                    int i = 0;
                    string[] sUrlList = new string[matches.Count];
                    // 取得匹配项列表 
                    foreach (Match match in matches)
                        sUrlList[i++] = match.Groups["imgUrl"].Value;
                    return sUrlList;
                }
            }
            return new[] { "" };
        }
        /// <summary>
        /// 过滤html标签
        /// </summary>
        /// <param name="html">要过滤的html字符串</param>
        /// <returns></returns>
        public static string FilterHtml(string html)
        {
            Regex regex1 = new Regex(@"<script[\s\S]+</script *>", RegexOptions.IgnoreCase);
            Regex regex2 = new Regex(@" href *= *[\s\S]*script *:", RegexOptions.IgnoreCase);
            Regex regex3 = new Regex(@" no[\s\S]*=", RegexOptions.IgnoreCase);
            Regex regex4 = new Regex(@"<iframe[\s\S]+</iframe *>", RegexOptions.IgnoreCase);
            Regex regex5 = new Regex(@"<frameset[\s\S]+</frameset *>", RegexOptions.IgnoreCase);
            Regex regex6 = new Regex(@"\<img[^\>]+\>", RegexOptions.IgnoreCase);
            Regex regex7 = new Regex(@"</p>", RegexOptions.IgnoreCase);
            Regex regex8 = new Regex(@"<p>", RegexOptions.IgnoreCase);
            Regex regex9 = new Regex(@"<[^>]*>", RegexOptions.IgnoreCase);
            Regex regex10 = new Regex(@"[\t\n\r\s]", RegexOptions.IgnoreCase);
            html = regex1.Replace(html, ""); //过滤<script></script>标记 
            html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性 
            html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件 
            html = regex4.Replace(html, ""); //过滤iframe 
            html = regex5.Replace(html, ""); //过滤frameset 
            html = regex6.Replace(html, ""); //过滤frameset 
            html = regex7.Replace(html, ""); //过滤frameset 
            html = regex8.Replace(html, ""); //过滤frameset 
            html = regex9.Replace(html, "");
            html = regex10.Replace(html, "");
            html = html.Replace("&nbsp;", "");
            html = html.Replace(" ", "");
            html = html.Replace("'", "''");    //转义单引号
            html = html.Replace("</strong>", "");
            html = html.Replace("<strong>", "");
            return html;
        }
    }
}
